csv = require 'csv'
fs = require 'fs'

module.exports = 
	parse : (filename, callback)->
		records = []
		errorRecords = []
		called = false
		csv().from.stream(fs.createReadStream(filename))
		.on 'record', (row,i)->
			unless i is 0
				companyName = row[0]
				jobName = row[1]
				salaries = (row[i] for i in [4..row.length] when row[i]?>0)
				if jobName and companyName and salaries.length > 0
					records.push {companyName,jobName,salaries}
				else 
					errorRecords.push row
		.on 'end', ()->
			unless called
				called = true
				callback null, records, errorRecords
		.on 'error', (err)->
			unless called
				called = true
				callback err, records, errorRecords

	parseRow: (record)->
		row = []
		row.push record.companyName
		row.push record.jobName
		row = row.concat record.salaries
		return row

	report: (records, callback)->
		r = []
		path = "/tmp/#{Math.random()*10000}.csv"
		try
			r.push(row.join(',')) for row in records 
			r = r.join '\n'
		catch e
			r = e

		csv().from(r).to.path(path)
		.on 'end', ()->
			callback null, path
